<!--
@description    表格展示
@author         秦俊强
@email          458112865@qq.com
@create         2021-06-07
-->

<template>
  <div class="content">
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="600"
      row-key="id"
      border
      stripe
      highlight-current-row
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        v-for="(itemHead, index) in tableHead"
        :key="index"
        :label="itemHead.label"
        :property="itemHead.prop"
        :align="index > 1 ? 'right' : ''"
        :width="index === 0 ? '45px' : ''"
      >
        <template slot-scope="scope">
          <template v-if="isArray(scope.row[scope.column.property])">
            <div
              v-for="(item, ind) in scope.row[scope.column.property]"
              :key="ind"
              :style="{ color: ind === 1 ? '#0AA372' : '' }"
            >
              <template v-if="ind === 0">
                <el-popover
                  popper-class="popoverClass"
                  placement="top"
                  trigger="click"
                >
                  <user-dialog
                    :userDialogData="userDialogData"
                    :step="'$ALL'"
                    :sliceStep="sliceStep"
                    :sliceByValues="sliceByValues"
                  ></user-dialog>
                  <el-button
                    class="stepUser"
                    type="text"
                    slot="reference"
                    @click="
                      selCurrentItem(item, index, itemHead, tableHead, scope)
                    "
                    >{{ item }}</el-button
                  >
                </el-popover>
              </template>
              <template v-else>
                {{ item }}
              </template>
            </div>
          </template>
          <template v-else>
            <template v-if="index === 0 || index === 1">
              {{ scope.row[scope.column.property] }}
            </template>
            <template v-else>
              <el-popover
                popper-class="popoverClass"
                placement="top"
                trigger="click"
              >
                <user-dialog
                  :userDialogData="userDialogData"
                  :step="'$ALL'"
                  :sliceStep="sliceStep"
                  :sliceByValues="sliceByValues"
                  :isViewFunnel="false"
                ></user-dialog>
                <el-button
                  class="stepUser"
                  type="text"
                  slot="reference"
                  @click="
                    selCurrentItem(null, index, itemHead, tableHead, scope)
                  "
                  >{{ scope.row[scope.column.property] }}
                </el-button>
              </el-popover>
            </template>
          </template>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>



<script>
/*用户列表弹框*/
import userDialog from "./userDialog";

export default {
  name: "table-funnel",
  components: { userDialog },
  props: {
    funnelReportResData: {
      type: Object,
      default: null,
    },
    userDialogData: {
      type: Object,
    },
  },

  data() {
    return {
      sliceStep: "",
      sliceByValues: [],
      tableHead: [
        // {prop: '', label: ''},
        //
        // {prop: 'title', label: '', sortable: true},
        // {prop: 'ALL', label: '总体转化', sortable: true},
        // {prop: 'commodityDetail', label: '浏览商口详情', sortable: true},
        // {prop: 'step1', label: '第 1 步转化', sortable: true},
        // {prop: 'step2', label: '第 2 步转化', sortable: true},
        // {prop: 'step3', label: '第 3 步转化', sortable: true},
      ],

      tableData: [
        // {
        //   id: 1,
        //   title: '总体',
        //   ALL: '88',
        //   commodityDetail: '01',
        //   step1: [1, 2],
        //   step2: '0102',
        //   step3: '0103',
        //
        //   children: [
        //     {
        //       id: '1-1',
        //       title: '20210101',
        //       ALL: '77',
        //       commodityDetail: '01-01',
        //       step1: '0101-01',
        //       step2: '0102-02',
        //       step3: '0103-03',
        //     },
        //     {
        //       id: '1-2',
        //       title: '20210102',
        //       ALL: '66',
        //       commodityDetail: '01-02',
        //       step1: '0101-04',
        //       step2: '0102-05',
        //       step3: '0103-06',
        //     }
        //   ]
        // }
      ],
    };
  },

  created() {
    let t = this;

    t.$watch("funnelReportResData", () => {
      // console.log('funnelReportResData = ', t.funnelReportResData);
      // console.log('funnelDetail = ', t.funnelReportResData.funnelDetail);

      t.tableHead = [];
      t.tableData = [];

      t.initTabHead();
    });
  },

  methods: {
    /*当前选择的方框 用于用户列表*/
    selCurrentItem(item, index, itemHead, tableHead, scope) {
      let sliceByValues = [];
      let sliceStep = "";
      /*第几列*/
      if (itemHead.prop !== "ALL") {
        sliceStep = index - 3;
      } else {
        sliceStep = tableHead.length - 3;
      }

      // /*按什么进行分组*/
      if (this.funnelReportResData.byFields.length !== 0) {
        let index = scope.$index + 1;
        let mainIndex = 0;
        for (let i = 0; i < this.tableData.length; i++) {
          index = index - this.tableData[i].children.length - 1;
          if (index <= 0) {
            /*选择的时间*/
            if (index !== -this.tableData[i].children.length) {
              // let date = this.tableData[mainIndex].children[(-(index+2))].title;
              let scoIndex = scope.$index + 1;
              for (let j = 0; j < i + 1; j++) {
                scoIndex = this.tableData[j].children.length - 1;
              }
              console.log("index---> " + index + "scoIndex --->" + scoIndex);
              let date = this.tableData[mainIndex].children[scoIndex].title;
              this.userDialogData.fromDate = date;
              this.userDialogData.toDate = date;
            }
            /*选择的条的主行*/
            mainIndex = i;
            break;
          }
        }
        /*主行的字段 [Android,Android]*/
        sliceByValues = this.tableData[mainIndex].title.split(",");

        if (sliceByValues === ["总体"]) {
          sliceByValues = ["$ALL"];
        } else {
          for (let i = 0; i < sliceByValues.length; i++) {
            sliceByValues[i] = sliceByValues[i].replace(/\s*/g, "");
          }
        }
      }
      this.sliceStep = sliceStep.toString();
      this.sliceByValues = sliceByValues;
    },
    /* 判断是否是数组 */
    isArray: (a) => {
      return Object.prototype.toString.call(a) === "[object Array]";
    },

    /* 初始化表头 */
    initTabHead() {
      let t = this;
      let events = t.funnelReportResData.events;

      for (let i = 0; i < events.length; i++) {
        if (i === 0) {
          t.tableHead.push({ prop: "", label: "" }); // 折叠展开箭头

          t.tableHead.push({ prop: "title", label: "" });
          t.tableHead.push({ prop: "ALL", label: "总体转化" });
          t.tableHead.push({ prop: events[i].eventId, label: events[i].cname });
        } else {
          t.tableHead.push({
            prop: events[i].eventId + i,
            label: "第 " + i + " 步转化",
          });
        }
      }
      t.initTabData();
    },

    /* 返回数组字符串 例：['a', null] => 'a, null' */
    getByValuesListStr(arr) {
      let str = "";

      for (let i = 0; i < arr.length; i++) {
        let val = arr[i];
        str = str + val + (i === arr.length - 1 ? "" : ", ");
      }

      return str;
    },

    /* 初始化表身数据 */
    initTabData() {
      let t = this;

      let byValues = t.funnelReportResData.byValues;
      let byValuesList = t.funnelReportResData.byValuesList;
      let funnelDetail = t.funnelReportResData.funnelDetail;
      let dateList = t.funnelReportResData.dateList;

      let events = t.funnelReportResData.events;
      let key = events[events.length - 1].eventId + (events.length - 1);

      // 表身数据 byValues 的 length 表示一共有多少主行数
      for (let i = 0; i < byValues.length; i++) {
        let tabTem = t.getTabTem(true);

        if (byValues[i] === "$ALL") {
          tabTem.title = "总体";
        } else {
          tabTem.title = t.getByValuesListStr(byValuesList[i]);
        }

        // 主行数 + 子行数
        for (let j = 0; j < funnelDetail.length; j++) {
          let cTabTem = t.getTabTem();
          let cItem = funnelDetail[j].overview[i];

          if (j === 0) {
            tabTem = t.getRowData(tabTem, cItem);
            continue;
          }

          cTabTem.title = dateList[j];
          cTabTem = t.getRowData(cTabTem, cItem);
          cTabTem["ALL"] = JSON.parse(JSON.stringify(cTabTem[key]));
          if (byValuesList.length === 1) {
            cTabTem["ALL"][1] = funnelDetail[j].completionRate + "%";
          } else {
            let item =
              funnelDetail[j].overview[i][funnelDetail[j].overview.length - 1]
                .convertedUser;

            let num =
              item === 0
                ? 0
                : (
                    (item / funnelDetail[j].overview[i][0].convertedUser) *
                    100
                  ).toFixed(2);

            cTabTem["ALL"][1] = num + "%";
          }

          tabTem.children.push(cTabTem);
        }
        tabTem["ALL"] = JSON.parse(JSON.stringify(tabTem[key]));
        if (byValuesList.length === 1) {
          tabTem["ALL"][1] = funnelDetail[0].completionRate + "%";
        } else {
          let item =
            funnelDetail[0].overview[i][funnelDetail[0].overview.length - 1]
              .convertedUser;

          let num =
            item === 0
              ? 0
              : (
                  (item / funnelDetail[0].overview[i][0].convertedUser) *
                  100
                ).toFixed(2);

          tabTem["ALL"][1] = num + "%";
        }

        t.tableData.push(tabTem);
      }
    },

    /* 返回表格行 */
    getRowData(resData, overview) {
      let events = this.funnelReportResData.events;

      for (let i = 0; i < events.length; i++) {
        let item = overview[i];
        let k = events[i].eventId;
        if (i === 0) {
          resData[k] = item.convertedUser;
        } else {
          k = k + i;
          resData[k] = [item.convertedUser, item.completionRate + "%"];
        }
      }
      return resData;
    },

    /* 返回表身数据模板 */
    getTabTem(b) {
      let tabTem = {};

      for (let i = 0; i < this.tableHead.length; i++) {
        let item = this.tableHead[i];

        // 标识唯一 id，方便折叠展开，和点击高亮行
        tabTem["id"] = Number(
          Math.random().toString().substr(3, 10) + Date.now()
        ).toString(36);

        if (item.prop) {
          tabTem[item.prop] = "";
        }

        if (b) {
          tabTem["children"] = [];
        }
      }

      return tabTem;
    },
  },
};
</script>



<style scoped lang="scss">
::v-deep .el-table tbody td {
  padding: 5px 0;
}
</style>
